Graph Representations

PolyU DSAI2201 Lecture 13 2025-11-25

Representing Connections in a Graph

Graphs are abstract structures of nodes and edges. To use them in a program, we need concrete data structures. The two most common are Adjacency Lists and Adjacency Matrices, each with distinct trade-offs.

  • Adjacency List: An array where each index corresponds to a vertex. The element at that index is a list of all vertices it connects to.
    • Pros: Space-efficient for sparse graphs (few edges), with space complexity of O(V+E)O(V+E). Iterating over a vertex's neighbors is fast.
    • Cons: Checking for a specific edge (u,v)(u, v) can be slow, taking up to O(degree(u))O(\text{degree}(u)) time.
  • Adjacency Matrix: A V×VV \times V matrix where cell (i,j)(i, j) is 1 if an edge exists from vertex ii to jj, and 0 otherwise.
    • Pros: Extremely fast edge lookup, taking O(1)O(1) time. Well-suited for dense graphs (many edges).
    • Cons: Requires O(V2)O(V^2) space regardless of the number of edges, which is very inefficient for sparse graphs.
📝 Interactive Quiz

1. What is the time complexity to check if an edge exists between two vertices in an Adjacency Matrix?

  • A) O(1)O(1)
  • B) O(V)O(V)
  • C) O(E)O(E)
  • D) O(V+E)O(V+E)

2. What is the space complexity of an Adjacency List for a graph with VV vertices and EE edges?

  • A) O(V2)O(V^2)
  • B) O(E2)O(E^2)
  • C) O(V+E)O(V+E)
  • D) O(V×E)O(V \times E)

3. For which type of graph is an Adjacency Matrix generally more space-efficient?

  • A) Sparse graphs (few edges)
  • B) Dense graphs (many edges)
  • C) Directed Acyclic Graphs
  • D) Bipartite graphs

4. You are modeling a social network with millions of users but relatively few connections per user. Which representation is better?

  • A) Adjacency Matrix
  • B) Adjacency List